package com.edwin.websitebe.controller;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.edwin.websitebe.model.Knowledge;
import com.edwin.websitebe.model.News;
import com.edwin.websitebe.service.KnowledgeService;
import com.edwin.websitebe.util.OSSUtil;
import com.edwin.websitebe.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/knowledge")
@Slf4j
public class KnowledgeController {

    @Autowired
    private KnowledgeService service;

    @GetMapping("")
    public ResultVO list(Knowledge knowledge) {

        Page<Knowledge> page = service.pageList(knowledge);

        return new ResultVO().success(page);
    }

    @PostMapping("")
    public ResultVO saveOrUpdate(@RequestBody Knowledge knowledge) {
        boolean result = service.saveOrUpdate(knowledge);
        return result ? new ResultVO().success() : new ResultVO().fail();
    }

    @GetMapping("/getById/{id}")
    public ResultVO getById(@PathVariable("id") Long id) {
        Knowledge knowledge = service.getById(id);
        return new ResultVO().success(knowledge);
    }

    @DeleteMapping("/delete")
    public ResultVO delete(@RequestParam Long id) {
        boolean result = service.removeById(id);
        return new ResultVO().success();
    }

    @PostMapping("/uploadCover")
    public ResultVO uploadCover(MultipartFile file, @RequestParam String id, HttpServletRequest request) throws IOException {
        log.info("开始上传知识封面: knowledgeId: {}", id);
        String filename = file.getOriginalFilename();
        String extend = filename.substring(filename.lastIndexOf("."));
        String objName = "img/knowledge/" + id + "-" + IdUtil.simpleUUID() + "-cover" + extend;
        String url = OSSUtil.uploadFile(objName, file);
        log.info("知识封面上传完成: newsId: {}, url: {}", id, url);
        log.info("开始更新知识数据");
        Knowledge knowledge = service.getById(id);
        knowledge.setImgUrl(url);
        service.updateById(knowledge);
        return new ResultVO().success();
    }

}
